<?php
class Record_service {
	
	private $ci;
	
	public function __construct()
	{
		$this->ci = & get_instance();
		$this->ci->load->model('tag_model');
		$this->ci->load->model('record_model');
		$this->ci->load->library('service/memory_service');
	}
	
	public function add_record($user_id, $memory, $description, $tag_name)
	{
		//find tag
		$tag = $this->ci->tag_model->get_tag_by_name($user_id, $tag_name);		
		
		//tag not exist add tag
		if(!$tag) $this->ci->tag_model->add_tag($user_id, $tag_name);
		
		//add record
		$record_id = $this->ci->record_model->add_record($user_id, $memory, $description, $tag_name);
		
		//add count
		$this->ci->tag_model->plus_count($user_id, $tag_name);
		
		//add memory
		$this->ci->memory_service->add_next_memory($record_id);
	}
	
	public function update_record($user_id, $record_id, $memory, $description, $tag_name)
	{
		//authenticate
		$record = $this->ci->record_model->get_record_by_id($record_id);
		if(!$record || $user_id != $record->userId) return false;
		
		//update tag count
		if($record->tag != $tag_name)
		{
			$this->ci->tag_model->minus_count($user_id, $record->tag);
			
			$tag = $this->ci->tag_model->get_tag_by_name($user_id, $tag_name);
			if(!$tag)
			{
				$this->ci->tag_model->add_tag($user_id, $tag_name);
			}
			$this->ci->tag_model->plus_count($user_id, $tag_name);
		}
		
		//update record
		$this->ci->record_model->update_record($record_id, $memory, $description, $tag_name);	
	}
	
	public function del_record($user_id, $record_id)
	{
		//authenticate
		$record = $this->ci->record_model->get_record_by_id($record_id);
		if(!$record || $user_id != $record->userId) return false;
		
		//minus tag count
		$tag = $this->ci->tag_model->get_tag_by_name($user_id, $record->tag);
		$this->ci->tag_model->minus_count($user_id, $record->tag);
		
		//del record
		$this->ci->record_model->del_record($record->recordId);
		
		//del memory
		$this->ci->memory_model->del_memory($record->recordId);
	}
	
	public function get_list_count_by_tag_id($user_id, $tag_id)
	{
		$tag;
		if($tag_id != 0)
		{
			$tag = $this->ci->tag_model->get_tag_by_id($tag_id);
			if(!$tag) return false;
		}

		//return tag count
		$tag_name = $tag_id == 0 ? '' : $tag->tagName;
		return $this->ci->record_model->get_list_count_by_tag($user_id, $tag_name);
	}
	
	public function get_list_by_tag_id($user_id, $tag_id, $from)
	{
		$tag;
		if($tag_id != 0)
		{
			$tag = $this->ci->tag_model->get_tag_by_id($tag_id);	
			if(!$tag) return false;
		}
		
		//return tag record
		$tag_name = $tag_id == 0 ? '' : $tag->tagName;
		return $this->ci->record_model->get_list_by_tag($user_id, $tag_name, $from);
	}
}
?>